<template>
  <div class="home">
    <!-- 头部navbar -->
    <van-nav-bar fixed class="nav">
      <template #right>
        <van-icon name="search" size="0.5rem" @click="btn" />
      </template>
      <template #left>
        <img class="logo" src="@/assets/images/logo.png" alt="" />
      </template>
    </van-nav-bar>
    <div class="home-show" v-if="isshow">
      <!-- tabs栏切换 -->
      <van-tabs
        v-model="active"
        animated
        class="tabs"
        offset-top="1.18rem"
        sticky
        swipeable
        @scroll="scrollTop"
      >
        <!-- 每个小的tab栏 -->
        <van-tab
          v-for="(item, index) in channelList"
          :title="item.name"
          :key="index"
          :name="item.id"
        >
          <!-- 上拉刷新功能 -->
          <van-pull-refresh v-model="isLoading" @refresh="onRefresh">
            <van-list
              v-model="loading"
              :finished="finished"
              finished-text="没有更多了"
              @load="onLoad"
              :immediate-check="false"
              class="lists"
            >
              <!-- 文章列表 -->
              <articleslist :lists="lists"></articleslist>
            </van-list>
          </van-pull-refresh>
        </van-tab>
      </van-tabs>
      <van-icon name="plus" class="moreChannels" @click="gochannel" />
    </div>
    <!-- 文章管理盒子 -->
    <van-popup v-model="show" :style="{ height: '100%', width: '100%' }">
      <Channelmanagement
        @back="back"
        :channelList="channelList"
        @add="add"
        @remove="remove"
        @move="move"
        ref="channelmanagement"
      ></Channelmanagement>
    </van-popup>
  </div>
</template>

<script>
import { getchannel } from '../../api/channel'
import { getArticlesItem, updatechannel } from '../../api/articles'
import articleslist from '@/components/connent/articleslist'
import Channelmanagement from '@/views/Channelmanagement/Channelmanagement'
import { mapState } from 'vuex'
import { Toast } from 'vant'
let cacheObj = {}
export default {
  // 组件名称
  name: 'home',
  // 组件参数 接收来自父组件的数据
  props: {},
  // 局部注册的组件
  components: { articleslist, Channelmanagement },
  // 组件状态值
  data () {
    Toast.loading({
      message: '加载中...',
      forbidClick: true,
    });
    return {
      isshow: false,
      channelList: [],
      active: 0,
      lists: [],
      isLoading: false,
      loading: false,
      finished: false,
      timestamp: null,
      show: false,
      scrollY: 0,
    }
  },
  computed: {
    ...mapState(['pinglunlengths'])
  },
  // 离开路由之前保存当前滚动的距离
  beforeRouteLeave (to, from, next) {
    // this.scrollY = document.documentElement.scrollTop
    from.meta.scrollY = window.scrollY
    next()
  },
  // 监听用户删除添加频道动作,当channelList改变的时候就会发送请求,修改用户的选择的频道
  watch: {
    async channelList (newvalue) {
      // 改造发送请求的新数组,需要有id和seq属性,不能有name属性并且不能有推荐
      const results = newvalue.reduce((sum, obj, index) => {
        const news = {
          id: obj.id,
          seq: index + 1
        }
        if (obj.id !== 0) {
          sum.push(news)
        }
        return sum
      }, [])
      await updatechannel(results)
    },
    // 监听vuex里的pinglunlengths文章评论条数的改变,重新赋值给home对应文章的评论数量属性
    pinglunlengths (newvalue) {
      const res = this.lists.find(ele => {
        return ele.art_id == newvalue.b
      })
      res.comm_count = newvalue.a
    },
    // 侦听 当前选择 的频道id
    active () {
      // 监听每个频道的滚动位置
      this.$nextTick(() => {
        window.scrollTo(0, cacheObj[this.active] && cacheObj[this.active].scrollY ? cacheObj[this.active].scrollY : 0)
      })
      // 切换频道，把 之前 的 lists清空，timestamp 设置 为 undefined（从第一页请求）
      // 每次切换频道的时候，active会变，就会触发watch的执行，
      // 先从上次缓存中取值相应频道的文章列表和timestamp，取到了就用，否则就走默认值
      this.lists = cacheObj[this.active] &&
        cacheObj[this.active].list ? cacheObj[this.active].list : []

      this.timestamp = cacheObj[this.active] &&
        cacheObj[this.active].timestamp
        ? cacheObj[this.active].timestamp : undefined

      // 在切换频道的时候，需要手动把 finished 设置为false，表示当前频道没有加载完毕，重新开始
      this.finished = false
      // 频道切换了，active 会 改变，就会触发 侦听器函数，只需要拿到最新的频道id，
      // 发送一次新的请求，拿到最新的数据，传给子组件lists即可
      this.getArticlesItemss(true)
    }
  },
  async activated () {
    // 请求it技术分类明细
    try {
      const res = await getchannel()
      this.channelList = res.data.data.channels
    } catch (error) {
      console.log(error)
    } finally {
    };
    // 请求默认显示推荐的文件item的内容
    await this.getArticlesItemss(true)
    this.isshow = true
    if (this.isshow == true) {
      Toast.clear()
    }
    // 当home页面处于活跃状态下滚动至保存的位置
    // window.scrollTo(0, this.scrollY)
    window.scrollTo(0, this.$route.meta.scrollY)
  },
  methods: {
    // 监听每个频道的滚动位置
    scrollTop ({ scrollTop }) {
      if (cacheObj[this.active] === undefined) {
        cacheObj[this.active] = {}
      }
      cacheObj[this.active].scrollY = scrollTop
    },
    // 请求频道文章数据功能
    async getArticlesItemss (is) {
      // 如果变量中有缓存就用缓存,不再发请求
      if (cacheObj[this.active] && cacheObj[this.active].list &&
        this.loading === false) {
        // console.log('缓存中有数据了，无需请求了')
        this.lists = cacheObj[this.active].list
        return
      }
      const resp = await getArticlesItem(this.active, this.timestamp)
      const { pre_timestamp, results } = resp.data.data
      if (pre_timestamp === null || results.length < 10) {
        this.finished = true
        return
      }
      this.timestamp = pre_timestamp
      if (is == true) {// 上拉加载更多
        this.lists = [...this.lists, ...results]
        // this.lists = this.lists.concat(...results)

        this.loading = false
        // console.log('缓存中没有数据, 请求数据结束')
      } else { // 下拉刷新
        // 把最新的数据 直接 替换 articleList
        this.lists = results
        // 关闭下拉加载状态，可以进行 再次 下拉刷新了
        this.isLoading = false
      }
      // 存入变量缓存
      if (cacheObj[this.active] === undefined) {
        cacheObj[this.active] = {}
      }
      cacheObj[this.active].list = this.lists
      cacheObj[this.active].timestamp = pre_timestamp
    },
    // 进入搜索页面
    btn () {
      this.$router.push('/search1')
    },
    // 上拉刷新
    onRefresh () {
      // 1. 发请求 2. 拿数据，合并
      // 2. 上拉刷新不走缓存
      cacheObj[this.active].list = null
      this.getArticlesItemss(false)
    },
    // 下拉加载更多
    async onLoad () {
      this.getArticlesItemss(true)
    },
    gochannel () {
      // 控制遮罩层开启
      this.show = true
    },
    // 关闭遮罩层功能
    back () {
      // 控制遮罩层关闭
      this.show = false
      // 优化 如果用户点击了频道管理里的编辑按钮,然后没有点击完成直接进入了首页,再次进入就会显示之前的叉号状态
      this.$refs.channelmanagement.is = false
    },
    // 添加频道功能
    add (obj) {
      this.channelList.push(obj)
    },
    // 删除频道功能
    remove (obj) {
      const res = this.channelList.filter(ele => {
        return ele !== obj
      })
      this.channelList = res
    },
    // 执行子组件的进入指定频道功能
    move (item) {
      this.active = item.id
      this.show = false
    }
  }
}
</script>
<style scoped lang="less">
.logo {
  width: 100px;
  height: 30px;
}
.van-icon-search {
  color: #fff;
}
.lists {
  margin-bottom: 46px;
}
.tabs {
  margin-top: 42px;
}
/deep/ .van-tabs__nav--line {
  padding-right: 20px;
}
.van-sticky--fixed {
  position: fixed;
  top: 0;
  right: 0;
  left: 0;
  z-index: 99;
}

/* 设置小图标的样式 */
.moreChannels {
  position: fixed;
  right: -2px;
  top: 68px;
  padding: 0 5px;
  margin-top: -10px;
  z-index: 999;
  background-color: #fff;
  font-size: 16px;
}
</style>
